<?php
namespace Home\Controller;
use User\Api\UserApi;
class WxController extends HomeController {
	private $_token='glgjssy';
	private $_appID='wx89cb84e211714b2c';
	private $_appsecret='64c9b922a6d6d850772943e36baa05d2';
	public function index(){
		$res=$this->checkSignature();
		if ($res && isset($_GET['echostr'])) {
			echo $_GET['echostr'];
		}else{
			$this->reply();
		}
	}
	private function checkSignature()
	{
		$signature=$_GET["signature"];
		$timestamp=$_GET["timestamp"];
		$nonce=$_GET["nonce"];

		$tmpArr = array($timestamp, $nonce,$this->_token );
		sort($tmpArr,SORT_STRING);
		$tmpArr=sha1(implode($tmpArr));

		if( $tmpArr==$signature ){
			return true;
		}else{
			return false;
		}
	}
	private function reply(){
		//获取xml信息
		$xml=$GLOBALS['HTTP_RAW_POST_DATA'];
		//将xml变成对象
		$obj=simplexml_load_string($xml);
		//判断是不是事件
		if ($obj->MsgType=='event') {
			//判断是否关注
			if ($obj->Event=='subscribe') {
				
				$content='欢迎来到方展的公众号';
				$this->textpush($obj,$content);

			}elseif ($obj->Event=='SCAN') {
				
			}

		}elseif ($obj->MsgType=='text') {
			switch ($obj->Content) {
				case '1':
				$content = $this->access_token();
				$this->textPush($obj,$content);
				break;

				case '2':
				$arr = array(
					array(
						'Title'=>'百度',	
						'Description'=>'百度一下，你就知道',
						'PicUrl'=>'https://www.baidu.com/img/bd_logo1.png',
						'Url'=>'https://www.baidu.com/'
						),
					array(
						'Title'=>'童话镇',	
						'Description'=>'网易云音乐，听见好声音',
						'PicUrl'=>'http://p1.music.126.net/tfa811GLreJI_S0h9epqRA==/3394192426154346.jpg?param=130y130',
						'Url'=>'http://music.163.com/#/song?id=432506345'
						),

					);
				$this->picTextPush($obj,$arr);
				break;
				default:
				if (mb_substr($obj->Content,-2)=='天气') {
					// $this->textPush($obj,mb_substr($obj->Content,0,-2));die;
					$content=$this->weather(mb_substr($obj->Content,0,-2));
					if($content['resultcode']==200){
						$this->weathermodel($content['result'],$obj->FromUserName);
					}
					else{
						$this->textPush($obj,$content['resultcode']);
					}
					
				}elseif (mb_substr($obj->Content,-2)=='影视') {
					$arr=$this->yellow(mb_substr($obj->Content,0,-2));
					$this->picTextPush($obj,$arr);
				}
				else{
					// $this->textPush($obj,mb_substr($obj->Content,-2));die;
					$content=$this->robot($obj->Content,$obj->FromUserName);
					$this->textPush($obj,$content);
				}
				
				break;
				
			}	
		}
		
	}

	//文字推送
	private function textPush($obj,$content){
		$str = '
		<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%d</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<Content><![CDATA[%s]]></Content>
		</xml>';
		
		echo sprintf($str,$obj->FromUserName,$obj->ToUserName,time(),'text',$content);
	}

	//图文推送
	private function picTextPush($obj,$arr){
		$str = '
		<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%d</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<ArticleCount>'.count($arr).'</ArticleCount>
			<Articles>';

				foreach ($arr as $v) {
					$str .= '<item>
					<Title><![CDATA['.$v['Title'].']]></Title>
					<Description><![CDATA['.$v['Description'].']]></Description>
					<PicUrl><![CDATA['.$v['PicUrl'].']]></PicUrl>
					<Url><![CDATA['.$v['Url'].']]></Url>
				</item>';
			}

			$str .=	'</Articles>
		</xml>';
		
		echo sprintf($str,$obj->FromUserName,$obj->ToUserName,time(),'news');

	}
	private function access_token(){
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appID}&secret={$this->_appsecret}";

		// return $this->curlSub($url)['access_token'];

		if (S('access_token1')==null) {
			$access_token=$this->curlSub($url);
			S('access_token1',$access_token['access_token'],$access_token['expires_in']-200);
		}
		return S('access_token1');
	}

	private function curlSub($url,$post){
        //1.初始化
		$ch = curl_init();

        //2.相关设置

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		if (stripos($url, "https://") !== false) {
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		}
		if($post != null){
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);	
		}

        //3.执行
		$res = curl_exec($ch);

        //当遇到错误的时候，我们可以将curl的错误打印出来
		if(curl_errno($ch) != 0){
			var_dump("错误号是".curl_errno($ch)."错误原因".curl_error($ch));
		}

        //4.关闭
		curl_close($ch);
       //json变成数组
		return json_decode($res,true);
	}
	public function creatmenu(){
		$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$this->access_token()}";
		// echo $url;die;
		$arr=[
		'button'=>[
		["type"=>"click",
		"name"=>"今日歌曲",
		"key"=>"k1",],
		["type"=>"click",
		"name"=>"影视影讯检索",
		"key"=>"k2",],
		
		['name'=>'菜单',
		"sub_button"=>[
		
		["type"=>"view",
		"name"=>"搜索",
		"url"=>"http://www.soso.com/"],
		
		
		["name"=> "发送位置", 
		"type"=> "location_select", 
		"key"=> "k3"],
		],
		],
		],
		];
		$res=$this->curlSub($url,$this->json_encode($arr));
		var_dump($this->json_encode($arr));
		var_dump($res);
	}
	public function delmenu(){
		$url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$this->access_token()}";
		$res=$this->curlSub($url);
	}
/**
     * 微信api不支持中文转义的json结构
     * @param array $arr
     */
public static function json_encode($arr)
{
	$parts   = array();
	$is_list = false;
        //Find out if the given array is a numerical array
	$keys       = array_keys($arr);
	$max_length = count($arr) - 1;
	if (($keys[0] === 0) && ($keys[$max_length] === $max_length)) {
            //See if the first key is 0 and last key is length - 1
		$is_list = true;
		for ($i = 0; $i < count($keys); $i++) {
                //See if each key correspondes to its position
			if ($i != $keys[$i]) {
                    //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ($arr as $key => $value) {
        	if (is_array($value)) {
                //Custom handling for arrays
        		if ($is_list) {
        			$parts[] = self::json_encode($value);
        		}
        		/* :RECURSION: */
        		else {
        			$parts[] = '"' . $key . '":' . self::json_encode($value);
        		}
        		/* :RECURSION: */
        	} else {
        		$str = '';
        		if (!$is_list) {
        			$str = '"' . $key . '":';
        		}

                //Custom handling for multiple data types
        		if (is_numeric($value) && $value < 2000000000) {
        			$str .= $value;
        		}
                //Numbers
        		elseif ($value === false) {
        			$str .= 'false';
        		}
                //The booleans
        		elseif ($value === true) {
        			$str .= 'true';
        		} else {
        			$str .= '"' . addslashes($value) . '"';
        		}
                //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
        		$parts[] = $str;
        	}
        }
        $json = implode(',', $parts);
        if ($is_list) {
        	return '[' . $json . ']';
        }
        //Return numerical JSON
        return '{' . $json . '}'; //Return associative JSON
    }
    public function robot($info,$userid){
    	$userid=substr($userid,-5);
    	$url="http://op.juhe.cn/robot/index?info={$info}&key=18c7dcaa501f00a193443e0d0bad3b31&userid={$userid}";

    	$res=$this->curlSub($url);
    	var_dump($res);
    	if ($res['result']['code']==100000) {
    		return $res['result']['text'];
    	}else{
    		die('错误');
    	} 
    }
    public function yellow($q){
    	$q=urlencode($q);
    	$url="http://op.juhe.cn/onebox/movie/video?key=0d2d1613ea3542896b9f69c9f1d7adb6&q={$q}";
    	$res=$this->curlSub($url);
    	// echo '<pre>';
    	// print_r($res['result']);
    	if ($res['error_code']==0) {
    		foreach ($res as $k => $v) {
    			$arr[$k]['Title']=$v['title'];
    			$arr[$k]['Description']=$v['desc'];
    			$arr[$k]['PicUrl']=$v['cover'];
    			$arr[$k]['Url']='http://www.gov.cn/';
    		}
    		return $arr;

    	}else{
    		die('错误');
    	}
    }
    public function weather($city){
    	$city=urlencode($city);
    	$url="http://v.juhe.cn/weather/index?format=2&cityname={$city}&key=eb6628c7670dff1ba96e70091e604d9f";
    	$res=$this->curlSub($url);
    	return $res;
    }


    public function weathermodel($res,$userid){
    	$arr = [
    	'touser'=>$userid,
    	'template_id'=>'8UG-chxazBJCee5Mct2znaC1-EQtV_KDg8ard5nEfs8',
    	'url'=>'http://www.weather.com.cn',
    	'data'=>[
    	'city'=>[
    	'value'=>$res['today']['city'],
    	'color'=>"",
    	],

    	'temp'=>[
    	'value'=>$res['today']['temperature'],
    	'color'=>"",
    	],

    	'wind_direction'=>[
    	'value'=>$res['sk']['wind_direction'],
    	'color'=>"",
    	],

    	'weather'=>[
    	'value'=>$res['today']['weather'],
    	'color'=>"",
    	],

    	'advice'=>[
    	'value'=>$res['today']['dressing_advice'],
    	'color'=>"",
    	],

    	],

    	];
    	$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token();
    	$this->curlSub($url,$this->json_encode($arr));
    }
    //临时二维码
    public function ertmp(){
    	$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$this->access_token()}";
    	$post= '{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}';
    	$res = $this->curlSub($url,$post);
    	$url2='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
    	return $url2.$res['ticket'];
    	// var_dump($res);
    }
    //永久二维码
    public function erfor(){
    	$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$this->access_token()}";
    	$post ='{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}';
    	$res = $this->curlSub($url,$post);
    	var_dump($res);
    	$url2='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
    	return $url2.$res['ticket'];
    }
}
?>